
from django import forms
from django.utils import timezone

from .models import ExerciseRecord, ExerciseGoal
from pytz import timezone as pytz_timezone


class ExerciseRecordForm(forms.ModelForm):
    class Meta:
        model = ExerciseRecord
        fields = ['type', 'start_time', 'end_time', 'calorie_cost']  # 指定要填写的字段
        widgets = {
            'start_time': forms.DateTimeInput(attrs={'type': 'datetime-local'}),
            'end_time': forms.DateTimeInput(attrs={'type': 'datetime-local'}),
        }

    def clean(self):
        cleaned_data = super().clean()
        start_time = cleaned_data.get('start_time')
        end_time = cleaned_data.get('end_time')
        calorie_cost=cleaned_data.get('calorie_cost')

        # 获取当前时间（默认为项目设置的时区时间）
        current_time = timezone.now()

        # 转换为其他时区
        beijing_time = current_time.astimezone(pytz_timezone('Asia/Shanghai'))
        print("beijing_time = " + str(beijing_time))

        # 去掉时区信息，只比较年月日时分秒
        if start_time:
            start_time_naive = start_time.replace(tzinfo=None)
        if end_time:
            end_time_naive = end_time.replace(tzinfo=None)
        beijing_time_naive = beijing_time.replace(tzinfo=None)
        #
        # # 调试输出去掉时区信息后的时间
        # print(f"Naive start_time: {start_time_naive}")
        # print(f"Naive end_time: {end_time_naive}")
        # print(f"Naive beijing_time: {beijing_time_naive}")

        # 检查开始时间和结束时间是否早于当前时间
        if start_time_naive and start_time_naive > beijing_time_naive:
            self.add_error('start_time', "开始时间不能晚于当前时间！")
        if end_time_naive and end_time_naive > beijing_time_naive:
            self.add_error('end_time', "结束时间不能晚于当前时间！")

        # 检查结束时间是否早于开始时间
        if start_time_naive and end_time_naive and end_time_naive < start_time_naive:
            self.add_error('end_time', "结束时间不能早于开始时间！")

        if calorie_cost <=0 :
            self.add_error('calorie_cost',"消耗卡路里必须大于0！")

        if calorie_cost >10000:
            self.add_error('calorie_cost',"建议单次运动消耗卡路里不超过10000！")


class ExerciseGoalForm(forms.ModelForm):
    class Meta:
        model = ExerciseGoal
        fields = ['type', 'start_time', 'end_time', 'target_calorie_cost']

        widgets = {
            'start_time': forms.DateTimeInput(attrs={'class': 'form-control', 'type': 'datetime-local'}),
            'end_time': forms.DateTimeInput(attrs={'class': 'form-control', 'type': 'datetime-local'}),
        }
